package com.example.playnote.fragment

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.example.playnote.R
import com.example.playnote.activity.ui.ContentActivity
import com.example.playnote.activity.ui.SearchActivity
import com.example.playnote.adapter.CommonAdapter
import com.example.playnote.adapter.CommonUseTagAdapter
import com.example.playnote.adapter.HotTagAdapter
import com.example.playnote.base.BaseFragment
import com.example.playnote.bean.Constant
import com.example.playnote.bean.FriendListResponse
import com.example.playnote.bean.HotKeyResponse
import com.example.playnote.bean.ToastFlag
import com.example.playnote.databinding.FragmentCommonBinding
import com.example.playnote.inflater
import com.example.playnote.toasty
import com.example.playnote.viewModel.HomeViewModel
import com.zhy.view.flowlayout.TagFlowLayout

class CommonUseFragment: BaseFragment<HomeViewModel, FragmentCommonBinding>() {
    private var isFirst: Boolean = true
    private lateinit var bookmarkTitle: TextView

    private var friendData: FriendListResponse? = null
    private var commonUseData: FriendListResponse?=null
    private var hotTagData: HotKeyResponse? = null
    private var bookmarkUseData: FriendListResponse ? = null
    /**
     *  adapter
     */
    private val commonAdapter: CommonAdapter by lazy {
        CommonAdapter(requireContext(), friendData)
    }

    /**
     * common use and hot key layout
     */
    private lateinit var flowLayout: LinearLayout
    /**
     * common use tag flowLayout
     */
    private var commonUseTagFlowLayout: TagFlowLayout? = null
    private var hotTagFlowLayout: TagFlowLayout? = null
    private var bookmarkTagFlowLayout: TagFlowLayout? = null

    override fun initView(savedInstanceState: Bundle?) {
        flowLayout = requireContext().inflater(R.layout.common_hot) as LinearLayout
        flowLayout.let {
            commonUseTagFlowLayout = it.findViewById(R.id.commonUseFlowLayout)
            bookmarkTagFlowLayout = it.findViewById(R.id.bookmarkFlowLayout)
            hotTagFlowLayout = it.findViewById(R.id.hotFlowLayout)
            bookmarkTitle = it.findViewById(R.id.bookmarkTitle)
        }
        mDatabind.commonSwipeRefreshLayout.run {
            isRefreshing = true
            setOnRefreshListener(onRefreshListener)
        }
        mDatabind.commonRecyclerView.run {
            layoutManager = LinearLayoutManager(requireContext())
            adapter = commonAdapter
        }
        commonAdapter.run {
            bindToRecyclerView(mDatabind.commonRecyclerView)
            addHeaderView(flowLayout)
        }
    }
    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden && isFirst) {
            mViewModel.getFriendList()
            mViewModel.getBookMark()
            mViewModel.getHotKeyList()
            isFirst = false
        }
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.friendList.observe(this) {
            if (it.errorCode != 0 ) {
                getFriendListFailed(it.errorMsg)
                return@observe
            }
            if (it.data.size == 0) {
                getFriendListZero()
                return@observe
            }
            commonAdapter.replaceData(it.data)
            commonUseData = it.data
            getFriendListSuccess(it.data)
        }
        mViewModel.bookMarkList.observe(this) {
            if (it.errorCode != 0 ) {
                getFriendListFailed(it.errorMsg)
                return@observe
            }
            if (it.data.size == 0) {
                getFriendListZero()
                return@observe
            }
            bookmarkUseData = it.data
            getBookMarkListSuccess(it.data)
        }
        mViewModel.hotKeyList.observe(this) {
            if (it.errorCode != 0 ) {
                getFriendListFailed(it.errorMsg)
                return@observe
            }
            if (it.data.size == 0) {
                getFriendListZero()
                return@observe
            }
            hotTagData = it.data
            getHotKeyListSuccess(it.data)
        }
    }

    private fun getHotKeyListSuccess(hotResult: HotKeyResponse) {
        hotTagFlowLayout?.run {
            adapter = HotTagAdapter(requireContext(), hotResult)
            setOnTagClickListener(onHotTagClickListener)
        }
    }

    private fun getBookMarkListSuccess(
        bookmarkResult: FriendListResponse
    ) {
        bookmarkResult.let {
            bookmarkTitle.visibility = View.VISIBLE
            bookmarkTagFlowLayout?.visibility = View.VISIBLE
            bookmarkTagFlowLayout?.run {
                adapter = CommonUseTagAdapter(requireContext(), bookmarkResult)
                setOnTagClickListener(onBookmarkTagClickListener)
            } ?: let {
                bookmarkTitle.visibility = View.GONE
                bookmarkTagFlowLayout?.visibility = View.GONE
            }
        }
    }

    /**
     * get Friend list Success
     */
    private fun getFriendListSuccess(
        commonResult: FriendListResponse,
    ) {
        commonUseTagFlowLayout?.run {
            adapter = CommonUseTagAdapter(requireContext(), commonResult)
            setOnTagClickListener(onCommonUseTagClickListener)
        }
        mDatabind.commonSwipeRefreshLayout.isRefreshing = false
    }

    /**
     * get Friend list Failed
     */
    private fun getFriendListFailed(errorMessage: String?) {
        requireContext().toasty(ToastFlag.ERROR, errorMessage?:getString(R.string.get_data_error))
        mDatabind.commonSwipeRefreshLayout.isRefreshing = false
    }

    /**
     * get Friend list data size equal zero
     */
    private fun getFriendListZero() {
        requireContext().toasty(ToastFlag.ERROR, getString(R.string.get_data_zero))
        mDatabind.commonSwipeRefreshLayout.isRefreshing = false
    }

    /**
     * refresh
     */
    fun refreshData() {
        mDatabind.commonSwipeRefreshLayout.isRefreshing = true
        mViewModel.getFriendList()
        mViewModel.getBookMark()
        mViewModel.getHotKeyList()
    }

    /**
     * RefreshListener
     */
    private val onRefreshListener = SwipeRefreshLayout.OnRefreshListener {
        refreshData()
    }

    /**
     * onBookmarkTagClickListener
     */
    private val onBookmarkTagClickListener = TagFlowLayout.OnTagClickListener { _, position, _ ->
        if (bookmarkUseData?.size != 0) {
            Intent(activity, ContentActivity::class.java).run {
                putExtra(Constant.CONTENT_URL_KEY, bookmarkUseData!![position].link)
                putExtra(Constant.CONTENT_ID_KEY, bookmarkUseData!![position].id)
                putExtra(Constant.CONTENT_TITLE_KEY, bookmarkUseData!![position].name)
                startActivity(this)
            }
        }
        true
    }

    /**
     * onCommonUseTagClickListener
     */
    private val onCommonUseTagClickListener = TagFlowLayout.OnTagClickListener { _, position, _ ->
        if (commonUseData?.size != 0) {
            Intent(activity, ContentActivity::class.java).run {
                putExtra(Constant.CONTENT_URL_KEY, commonUseData!![position].link)
                putExtra(Constant.CONTENT_ID_KEY, commonUseData!![position].id)
                putExtra(Constant.CONTENT_TITLE_KEY, commonUseData!![position].name)
                startActivity(this)
            }
        }
        true
    }
    /**
     * hot onCommonUseTagClickListener
     */
    private val onHotTagClickListener = TagFlowLayout.OnTagClickListener { _, position, _ ->
        if (hotTagData?.size != 0) {
            Intent(activity, SearchActivity::class.java).run {
                putExtra(Constant.SEARCH_KEY, true)
                putExtra(Constant.CONTENT_TITLE_KEY, hotTagData!![position].name)
                startActivityForResult(this, Constant.MAIN_LIKE_REQUEST_CODE)
            }
        }
        true
    }

    override fun lazyLoadData() {
    }
}